from django.shortcuts import render, redirect
from .models import *

# Create your views here.
#登录
def to_login_page(request):
    return render(request, "login.html")
def login_view(request):
    username_get = request.POST.get('username', '')
    password_get = request.POST.get('password', '')
    print(username_get + " " + password_get)
    if username_get and password_get:
        query_result_count = User.objects.filter(username = username_get, password = password_get).count()
        if query_result_count >= 1:
            return redirect('/mysql_demo/')
        else:
            error_info = '用户名或密码输入错误！请重试！'
            return render(request, "login.html", {'error_info': error_info})
    else:
        error_info = '用户名和密码不能为空！请重试！'
        return render(request, "login.html", {'error_info':error_info})

# 注册
def to_register_page(request):
    return render(request, "register.html")
def register_view(request):
    username_get = request.POST.get('username', '')
    password_get = request.POST.get('password', '')
    confirmed_password_get = request.POST.get('confirmed_password', '')
    if username_get and password_get and confirmed_password_get:
        query_result_count = User.objects.filter(username = username_get).count()
        if query_result_count >= 1:
            error_info = '用户名已存在！请重试！'
            return render(request, "register.html", {'error_info': error_info})
        else:
            if len(username_get) > 20:
                error_info = '用户名长度不可超过 20 字符！请重试！'
                return render(request, "register.html", {'error_info': error_info})
            elif len(password_get) > 20 or len(password_get) < 8:
                error_info = '密码长度应在 8 字符和 20 字符之间！请重试！'
                return render(request, "register.html", {'error_info': error_info})
            elif username_get == password_get:
                error_info = '用户名和密码不可相同！请重试！'
                return render(request, "register.html", {'error_info': error_info})
            elif password_get != confirmed_password_get:
                error_info = '确认密码与原密码不匹配！请重试！'
                return render(request, "register.html", {'error_info': error_info})
            else:
                new_user = User(username=username_get, password=password_get)
                new_user.save()
                return redirect("/login/")
    else:
        error_info = '用户名和密码不能为空！请重试！'
        return render(request, "register.html", {'error_info': error_info})